package cn.openea.perpartner.meily.web.service.importandexport;

import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.utils.poi.ExcelUtil;
import cn.openea.perpartner.meily.constant.CommonConstants;
import cn.openea.perpartner.meily.constant.enums.ExpressCompany;
import cn.openea.perpartner.meily.constant.enums.LogisticsModule;
import cn.openea.perpartner.meily.web.entity.GroupBuyingSub;
import cn.openea.perpartner.meily.web.entity.dto.GroupBuyingSubDTOFactory;
import cn.openea.perpartner.meily.web.entity.dto.GroupBuyingSubDTOFactory.ShipmentTemplateDTO;
import cn.openea.perpartner.meily.web.entity.dto.ImportErrMsgDTO;
import cn.openea.perpartner.meily.web.entity.vo.ExportDataVo;
import cn.openea.perpartner.meily.web.entity.vo.OrderRecordVo;
import cn.openea.perpartner.meily.web.service.IGroupBuyingSubService;
import cn.openea.perpartner.meily.web.service.logistics.businessModule.LogisticsModlueHandler;
import cn.openea.perpartner.meily.web.service.logistics.businessModule.LogisticsModuleService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ysk
 * @version 1.0.1
 * @Description 团购批量发货
 * @createTime 2023年05月16日 22:51:00
 */
@Slf4j
@Service(value = CommonConstants.IMPORTANDEXPORT.GROUPBUY_BATCH_DELIVERY)
public class GroupBuyBatchDeliveryService extends ImportAndExportAbstractService {

    @Resource
    private IGroupBuyingSubService groupBuyingSubService;
    @Resource
    private GroupBuyingSubDTOFactory groupBuyingSubDTOFactory;
    @Resource
    private LogisticsModlueHandler logisticsModlueHandler;

    @Override
    public void exportExcel(ExportDataVo exportDataVo, HttpServletResponse response) {
        // 发货模板默认查询的是待发货的数据
        List<GroupBuyingSub> groupBuyingSubs;
        if (exportDataVo.byIds()) {
            groupBuyingSubs = groupBuyingSubService.selectByIdsAndOrderState(exportDataVo.getBatchIds(), "已付款");
        } else {
            OrderRecordVo recordVo = JSONObject.parseObject(JSONObject.toJSONString(exportDataVo.getQueryVO()), OrderRecordVo.class);
            if (recordVo == null) {
                recordVo = new OrderRecordVo();
            }
            // 默认查询未发货，同时过滤掉meily人员的测试数据
            recordVo.setOrderStatus("已付款");
            recordVo.setFilterTestOrder(true);
            groupBuyingSubs = groupBuyingSubService.selectList(recordVo);
        }
        List<ShipmentTemplateDTO> shipmentTemplateDTOS = groupBuyingSubs
                .parallelStream()
                .map(item -> groupBuyingSubDTOFactory.toShipmentTemplateDTO.apply(item))
                .collect(Collectors.toList());
        ExcelUtil<ShipmentTemplateDTO> util = new ExcelUtil<>(ShipmentTemplateDTO.class);
        util.exportExcel(response, shipmentTemplateDTOS, "订单批量发货模板.xlsx");
    }

    @Override
    protected ImportErrMsgDTO handleSingleExcel(@NonNull Object obj) {
        ShipmentTemplateDTO shipmentTemplateDTO = (ShipmentTemplateDTO) obj;
        try {
            if (StringUtils.isBlank(shipmentTemplateDTO.getConsigneeName()) || StringUtils.isBlank(shipmentTemplateDTO.getCourierNumber())) {
                throw new ServiceException("快递公司或快递单号为空");
            }
            ExpressCompany expressCompany = ExpressCompany.findMostSimilarElement(shipmentTemplateDTO.getCourierName());
            GroupBuyingSub groupBuyingSub = groupBuyingSubService.getOne(new LambdaQueryWrapper<GroupBuyingSub>()
                    .eq(GroupBuyingSub::getOrderId, shipmentTemplateDTO.getOrderId()));
            if (groupBuyingSub == null) {
                throw new ServiceException("团购数据不存在");
            }
            LogisticsModuleService service = logisticsModlueHandler.getService(LogisticsModule.GROUPBUY);
            service.logisticsChange(expressCompany, groupBuyingSub.getId(), shipmentTemplateDTO.getCourierNumber());
        } catch (Exception e) {
            return ImportErrMsgDTO.builder()
                    .id(shipmentTemplateDTO.getOrderId())
                    .errMsg(e.getMessage())
                    .build();
        }
        return null;
    }
}
